﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Perceiveit.Xml.Tests.Serialized
{
    public class XSerializerPerformance
    {
        private const string Category = "XmlSerializer";

        public PerformanceRun TestPerformance()
        {
            DateTime newDt = DateTime.Now;
            Guid newGuid = Guid.NewGuid();
            string xml = Properties.Resources.Sample;
            PerformanceRun set = new PerformanceRun(Category);
            set.Begin();

            Root root = LoadRoot(xml);
            set.Mark("Load Root");

            int i = root.IntegerValue;
            string s = root.StringValue;
            Guid g = root.GuidValue;
            bool? b = root.BoolValue;
            DbType db = root.DbTypeValue;
            Byte by = root.ByteValue;
            char c = root.CharValue;
            DateTime dt = root.DateValue;

            set.Mark("Read Attributes");

            root.IntegerValue = 10;
            root.StringValue = "New String";
            root.GuidValue = newGuid;
            root.BoolValue = false;
            root.ByteValue = 1;
            root.DbTypeValue = DbType.Object;
            root.CharValue = 'c';
            root.DateValue = newDt;

            set.Mark("Write Attributes");

            i = root.IntegerValue;
            s = root.StringValue;
            g = root.GuidValue;
            b = root.BoolValue;
            db = root.DbTypeValue;
            by = root.ByteValue;
            c = root.CharValue;
            dt = root.DateValue;

            set.Mark("Read Again");

            using (System.IO.StringWriter sw = new System.IO.StringWriter())
            {
                System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(Root));
                ser.Serialize(sw, root);
            }

            set.Mark("To Xml Writer");
            set.End();

            return set;
        }

        private static Root LoadRoot(string xml)
        {
            Root root;
            using (System.IO.StringReader sr = new System.IO.StringReader(xml))
            {
                System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(Root));
                root = ser.Deserialize(sr) as Root;
            }
            
            return root;
        }
    }
}
